<?php

namespace MLM\Controller;

use Zend\View\Model\ViewModel;
use Zend\Authentication\Result;
use Zend\Authentication\AuthenticationService;
use Zend\Authentication\Adapter\DbTable as AuthAdapter;

class NetworkController extends \MLM\Model\Generic\Controller {

    public function indexAction() {
        
        $identity = $this->hasSession();
        $this->layout('layout/member');

        $view = new ViewModel();
        
        $storage = new \MLM\Model\Network\Storage($this->_db);
        
        $formData = $this->getRequest()->getPost();

        $memberId = $identity->member_id;
        $key = (isset($formData['key'])) ? $formData['key'] : $memberId;
        $isAjax = (isset($formData['ajax'])) ? $formData['ajax'] : "";

        $dataParent = $storage->getMemberDetail($key);

        while($dataParent->next()){
            $parent = $dataParent->current();
            $parentSponsorId = $parent['sponsor_id'];
            $parentCode = $parent['member_code'];
            $parentMatrix = $parent['matrik1_id'];
            $parentName = $parent['member_name'];

            $parentMobileNo = $parent['mobile_no'];
            
        }

        //jaringan by sponsor_id
        $tmpsp = "";

        $dataChildSp = $storage->getSponsorNetwork('member_id', $parentSponsorId, $parentCode);

        $tmpsp .= $dataChildSp['tree']."\n";
        

        //jaringan by matrix1_id

        $tmp = "";

        if ($parentMatrix > 0){
            $view->setVariable('parent', 1);
            $tmp = "<span id='uplineContent'><a href='javascript: void(0)' onclick=\"getChild('child-".$parentMatrix."')\">UPLINE</a></span>";
        }

        $tmp .= "<li title='<center>".strtoupper($parentCode."<br>".$parentName)."</center>' class='bigtri'><br>".$parentCode;
        $tmp .= "<ul id='ul-matrix' class='hide'>\n";

        $dataChild = $storage->getMemberNetwork('matrik1_id', $key, $parentCode);

        $numChild = 0;
        while($dataChild->next()){
            $res = $dataChild->current();
            $numChild++;
            
            $tmp .= "<li title='<center>".strtoupper($res['member_name']."<br>".$res['member_code'])."</center>' data-actor='child-".$res['member_id']."' class='bigtri' ><br>".$res['member_code'];

            $tmp .= "<ul id='ul-matrix' class='hide'>\n";
            $dataChild2 = $storage->getMemberNetwork('matrik1_id', $res['member_id'], $res['member_code']);
            
            $numChild2 = 0;
            while($dataChild2->next()){
                $numChild2++;
                $res2 = $dataChild2->current();
                
                $tmp .= "<li title='<center>".strtoupper($res2['member_name']."<br>".$res2['member_code'])."</center>' data-actor='child-".$res2['member_id']."' class='bigtri' ><br>".$res2['member_code'];

                
            }

            if ($numChild2 < 5){

                //for ($xx = 5; $xx > $numChild2; $xx--){
                    $tmp .= "<li title='<center>Add Member<br></center>' data-actor='add-".$res['member_id']."' class='bigtri' ><br>Add";
                //}

            }

            $tmp .= "</ul>\n";
            $tmp .= "</li>\n";
        }

        if ($numChild < 5){

            //for ($yy = 5; $yy > $numChild; $yy--){
                $tmp .= "<li title='<center>Add Member<br></center>' data-actor='add-".$key."' class='bigtri' ><br>Add";
            //}
            
        }

        $tmp .= "</ul>\n";
        $tmp .= "</li>\n";

        if ($isAjax == 1){
            $view->setTerminal(true);
        }

        $view->setVariable('identity', $identity);
        $view->setVariable('uplines', $uplines);
        $view->setVariable('dataParent', $dataParent);
        $view->setVariable('sponsorId', $parentSponsorId);
        $view->setVariable('sponsor', $tmpsp);
        $view->setVariable('matrix', $tmp);
        $view->setVariable('isAjax', $isAjax);
        $view->setVariable('numChild', $numChild);


        //Get Messages Notif
        $this->getMsgNotif($identity->member_type_id, $memberId);
        
        return $view;        
    }


    public function binaryAction()
    {
        $identity = $this->hasSession();
        $this->layout('layout/member');

        $view = new ViewModel();

        $storage = new \MLM\Model\Network\Storage($this->_db);

        $formData = $this->getRequest()->getPost();
                
        $memberId = $identity->member_id;
        $key = (isset($formData['key'])) ? $formData['key'] : $memberId;
        $sBy = (isset($formData['sBy'])) ? $formData['sBy'] : "member_id";
        $isAjax = (isset($formData['ajax'])) ? $formData['ajax'] : "";

         
        $dataParent = $storage->getMemberDetail($key);

        while($dataParent->next()){
            $parent = $dataParent->current();
            $parentSponsorId = $parent['sponsor_id'];
            $parentCode = $parent['member_code'];
            $parentMatrix = $parent['matrik1_id'];
            $parentName = $parent['member_name'];
            $parentMobileNo = $parent['mobile_no'];
            $parentID = $parent['member_id'];
            $parentID2 = $parent['parent_id'];
            $memberStts = $parent['status_id'];
            $memberTypeId = $parent['member_type_id'];
            $subsAmount = $parent['subs_amount'];
        }

        
        $tmp = "";
        if ($parentMatrix > 0 || $parentID = 100){
            $tmp = "<ul id='organisation'>\n";

            if ($parentID2 != "" && $parentID != $identity->member_id){
                //$tmp .= "<span id='uplineContent'><a href='".Zend_Controller_Front::getInstance()->getBaseUrl()."/member/binary/sBy/member_id/key/".$dataParent[0]['parent_id']."'>Upline</a></span>";

                $view->setVariable('parent', 1);
                $tmp = "<span id='uplineContent'><!--a href='javascript: void(0)' onclick=\"getChild('child-".$parentMatrix."')\">UPLINE</a-->";

                $tmp .= "<button type='button' class='btn btn-info' onclick=\"getChild('child-".$parentMatrix."')\">
                        <i class='icon-arrow-up'></i>
                        </button></span>
                        ";
            }

            $imgPic = ($memberStts == 2) ? "pic-member-active.png" : "pic-member-inactive.png";
            //$stts = ($memberStts == 2) ? "Active" : "Inactive";

            $detailStts = "";
            if ($memberStts == 2){

                $sqlP = "select member_type_name,
                (select member_type_name
                from member_type where member_type_id = mt.parent_member_type_id) as pkg
                from member_type mt where member_type_id = ?";

                $stmtP = $this->_db->query($sqlP);
                $resultP = $stmtP->execute(array($memberTypeId));
                while($resultP->next()){
                    $resP = $resultP->current();
                    $detailStts = "Package: ".$resP["pkg"]."<br>Plan: ".$resP["member_type_name"]."<br>Amount: ".number_format($subsAmount, 2, '.', ',');
                }
            }

            $stts = ($memberStts == 2) ? "<center>Active<br>".$detailStts."<center>" : "Inactive";

            $tmp .= "<li class='big' title='".$stts."'> <br><img src='/img/".$imgPic."'/>\n";
            $tmp .= "<br><br> ".$parentCode." <br> ".$parentName."\n";

            $dataChild = $storage->getMemberBinary('parent_id', $parentID, $parentCode);

            $tmp .= $dataChild."
                    </li>\n";

            $tmp .= "</ul>\n";

        }
        //$view->setTerminal(true);

        $view->setVariable('id', $tmp);
        
        if ($isAjax == 1){
            
            $view->setTerminal(true);
        }

        $view->setVariable('isAjax', $isAjax);
        $view->setVariable('numChild', $numChild);

        //Get Messages Notif
        $this->getMsgNotif($identity->member_type_id, $memberId);
        $this->layout()->navMenu = "<li class='active'>My Team</li> <li class='active'>Genealogy Tree </li>";
        return $view;
    }


    
    


    public function trinaryAction() {

        $identity = $this->hasSession();
        $this->layout('layout/member');

        $view = new ViewModel();

        $storage = new \MLM\Model\Network\Storage($this->_db);

        $formData = $this->getRequest()->getPost();

        $memberId = $identity->member_id;
        $key = (isset($formData['key'])) ? $formData['key'] : $memberId;
        $isAjax = (isset($formData['ajax'])) ? $formData['ajax'] : "";

        $dataParent = $storage->getMemberDetail($key);

        while($dataParent->next()){
            $parent = $dataParent->current();
            $parentSponsorId = $parent['sponsor_id'];
            $parentCode = $parent['member_code'];
            $parentMatrix = $parent['matrik1_id'];
            $parentName = $parent['member_name'];

            $parentMobileNo = $parent['mobile_no'];

        }

        //jaringan by matrix3_id

        $tmp = "";

        if ($parentMatrix > 0){
            $view->setVariable('parent', 1);
            $tmp = "<span id='uplineContent'><a href='javascript: void(0)' onclick=\"getChild('child-".$parentMatrix."')\">UPLINE</a></span>";
        }

        $tmp .= "<li title='<center>".strtoupper($parentCode."<br>".$parentName)."</center>' class='small'><br>".$parentCode;
        $tmp .= "<ul id='ul-matrix' class='hide'>\n";

        $dataChild = $storage->getMemberTrinary('matrik3_id', $key, $parentCode);

        $numChild = 0;
        while($dataChild->next()){
            $res = $dataChild->current();
            $numChild++;

            $tmp .= "<li title='<center>".strtoupper($res['member_name']."<br>".$res['member_code'])."</center>' data-actor='child-".$res['member_id']."' class='small' ><br>".$res['member_code'];

            $tmp .= "<ul id='ul-matrix' class='hide'>\n";
            $dataChild2 = $storage->getMemberTrinary('matrik3_id', $res['member_id'], $res['member_code']);

            $numChild2 = 0;
            while($dataChild2->next()){
                $numChild2++;
                $res2 = $dataChild2->current();

                $tmp .= "<li title='<center>".strtoupper($res2['member_name']."<br>".$res2['member_code'])."</center>' data-actor='child-".$res2['member_id']."' class='small' ><br>".$res2['member_code'];

                $tmp .= "<ul id='ul-matrix' class='hide'>\n";
                $dataChild3 = $storage->getMemberTrinary('matrik3_id', $res2['member_id'], $res2['member_code']);

                $numChild3 = 0;
                while($dataChild3->next()){
                    $numChild3++;
                    $res3 = $dataChild3->current();

                    $tmp .= "<li title='<center>".strtoupper($res3['member_name']."<br>".$res3['member_code'])."</center>' data-actor='child-".$res3['member_id']."' class='small' ><br>".$res3['member_code'];


                }

                $tmp .= "</ul>\n";
                $tmp .= "</li>\n";
            }
            
            $tmp .= "</ul>\n";
            $tmp .= "</li>\n";
        }        

        $tmp .= "</ul>\n";
        $tmp .= "</li>\n";

        if ($isAjax == 1){
            $view->setTerminal(true);
        }

        $view->setVariable('identity', $identity);
        $view->setVariable('uplines', $uplines);
        $view->setVariable('dataParent', $dataParent);
        $view->setVariable('sponsorId', $parentSponsorId);
        $view->setVariable('matrix', $tmp);
        $view->setVariable('isAjax', $isAjax);
        $view->setVariable('numChild', $numChild);


        //Get Messages Notif
        $this->getMsgNotif($identity->member_type_id, $memberId);

        return $view;
    }

    public function sponsorAction() {

        $identity = $this->hasSession();
        $this->layout('layout/member');

        $getParams = $this->getRequest()->getQuery();
        $memberId = (isset($getParams['memberId'])) ? $getParams['memberId'] : $identity->member_id;
        $isAjax = (isset($getParams['isAjax'])) ? $getParams['isAjax'] : "";
        $upline = (isset($getParams['upline'])) ? $getParams['upline'] : "";

        $storage = new \MLM\Model\Network\Storage($this->_db);
        $data = $storage->getSponsor($memberId);

        $view = new ViewModel();

        if ($isAjax == 1) $view->setTerminal(true);

        $view->setVariable('memberId', $memberId);
        $view->setVariable('upline', $upline);
        $view->setVariable('memberLogin', $identity->member_id);
        $view->setVariable('isAjax', $isAjax);
        $view->setVariable('data', $data);

        

        //Get Messages Notif
        $this->getMsgNotif($identity->member_type_id, $identity->member_id);

        return $view;
    }


    public function referralsAction() {

        $identity = $this->hasSession();
        $this->layout('layout/member');

        
        $view = new ViewModel();

        //Get Messages Notif
        $this->getMsgNotif($identity->member_type_id, $identity->member_id);
        $this->layout()->navMenu = "<li class='active'>My Team</li> <li class='active'>Direct Referrals  </li>";
        return $view;
    }


    public function alldownlineAction() {

        $identity = $this->hasSession();
        $this->layout('layout/member');


        $view = new ViewModel();

        //Get Messages Notif
        $this->getMsgNotif($identity->member_type_id, $identity->member_id);
        $this->layout()->navMenu = "<li class='active'>My Team</li> <li class='active'>All Downline </li>";
        return $view;
    }

    public function leftdownlineAction() {

        $identity = $this->hasSession();
        $this->layout('layout/member');


        $view = new ViewModel();

        //Get Messages Notif
        $this->getMsgNotif($identity->member_type_id, $identity->member_id);
        $this->layout()->navMenu = "<li class='active'>My Team</li> <li class='active'>Left Downline </li>";
        return $view;
    }


    public function rightdownlineAction() {

        $identity = $this->hasSession();
        $this->layout('layout/member');


        $view = new ViewModel();

        //Get Messages Notif
        $this->getMsgNotif($identity->member_type_id, $identity->member_id);
        $this->layout()->navMenu = "<li class='active'>My Team</li> <li class='active'>Right Downline </li>";
        return $view;
    }


    //Get Messages Notif
    private function getMsgNotif($memberTypeId, $memberId){


        if ($memberId == 100) $memberId2 = $memberId;
        else{
            $identity = $this->hasSession();
            //$memberId2 = ($identity->member_reff_id == "") ? $memberId : $identity->member_reff_id;
            $memberId2 = $memberId;
            $isAgent = $identity->member_reff_id;
        }


        $notifStorage = new \MLM\Model\Notification\Storage($this->_db);
        $notifMsg = new \MLM\Model\Notification($notifStorage);
        $newMsgCnt = $notifMsg->getCountNewMsg($memberId);
        $newMsgList = $notifMsg->getNewMsgList($memberId);
        $newAlertCnt = $notifMsg->getCountAlertApproval($memberTypeId, $memberId2, $isAgent);
        $newAlertList = $notifMsg->getAlertApproval($memberTypeId, $memberId2, $isAgent);

        $action = $this->getEvent()->getRouteMatch()->getParam('action');
        $control = $this->getEvent()->getRouteMatch()->getParam('controller');

        $this->layout()->menu = $control.'\\'.$action;
        $this->layout()->newMsgCnt = $newMsgCnt;
        $this->layout()->newMsgList = $newMsgList;
        $this->layout()->newAlertCnt = $newAlertCnt;
        $this->layout()->newAlertList = $newAlertList;

    }

    private function hasSession() {
        $auth = new AuthenticationService();

        $identity = $auth->getIdentity();

        if (!$auth->hasIdentity()) {
            return $this->redirect()->toRoute('application/default', array('controller' => 'Index', 'action' => 'login'));
        } else {
            return $auth->getIdentity();
        }
    }

}
